package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.thread.WmThreadLocal;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;


@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private FileStorageService fileStorageService;

    @Override
    public ResponseResult delPictureById(Integer id) {
        if (id==null||id<=0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial obj = getById(id);
        if (obj==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String url = obj.getUrl();
        fileStorageService.delete(url);
        removeById(id);
        return ResponseResult.okResult("删除成功");
    }

    @Override
    public ResponseResult cancel_collect(Integer id) {
        if (id==null||id<=0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial material = wmMaterialMapper.selectOne(Wrappers.lambdaQuery(WmMaterial.class)
                .eq(WmMaterial::getId, id));
        if (material == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Short isCollection = material.getIsCollection();
        if (isCollection!=0) {
            material.setIsCollection(((short) 0));
            updateById(material);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 素材收藏
     * @param id 素材id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        if (id==null||id<=0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial material = wmMaterialMapper.selectOne(Wrappers.lambdaQuery(WmMaterial.class)
                .eq(WmMaterial::getId, id));
        if (material == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Short isCollection = material.getIsCollection();
        if (isCollection!=1) {
            material.setIsCollection(((short) 1));
            updateById(material);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        dto.checkParam();
        Page<WmMaterial> page=new Page<>(dto.getPage(),dto.getSize());
        Page<WmMaterial> list = baseMapper.selectPage(page,
                Wrappers.lambdaQuery(WmMaterial.class).
                        eq(!ObjectUtils.isEmpty(dto.getIsCollection()) && dto.getIsCollection() == 1,
                                WmMaterial::getIsCollection, dto.getIsCollection())
                        .eq(WmMaterial::getUserId, WmThreadLocal.getUser().getId())
                        .orderByDesc(WmMaterial::getCreatedTime)
        );
        return new PageResponseResult(dto.getPage(),dto.getSize(), (int) list.getTotal()).ok(list.getRecords());
    }

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        try {
            if(multipartFile==null||multipartFile.isEmpty()){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            String originalFilename = multipartFile.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString().replace("-","")
                    .concat(suffix);
            String url = fileStorageService.uploadImgFile("",
                   fileName,
                    multipartFile.getInputStream());
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUrl(url);
            wmMaterial.setUserId(WmThreadLocal.getUser().getId());
            wmMaterial.setCreatedTime(new Date());
            wmMaterial.setIsCollection((short) 0);
            wmMaterial.setType((short) 1);
            wmMaterialMapper.insert(wmMaterial);
            return ResponseResult.okResult(url);
        } catch (IOException e) {
            log.error("WmMaterialServiceImpl 上传图片失败");
            throw new RuntimeException(e);
        }
    }
}
